<?php

class AuthController extends BaseController {
    public function actionLogin() {
        if(Yii::app()->request->isAjaxRequest && Yii::app()->request->isPostRequest) {
            $username = Yii::app()->request->getPost('username', '');
            $password = Yii::app()->request->getPost('password', '');
            if (empty($username) || empty($password)) {
                $this->error('用户名或密码不能为空');
            }
            $admin = Admin::model()->find('username=:username', array(':username'=>$username));
            if (is_null($admin)) {
                $this->error('用户名或密码错误');
            }
            $login_ret = $admin->login($password);
            if ($login_ret === false) {
                $this->error($admin->getError('login'));
            }
            $this->success('登录成功');
        } else {
            $this->render('login');
        }
    }

    /**
     * 退出登录
    */
    public function actionLogout() {
        $session = Yii::app()->session;
        $url = $this->createUrl('auth/login');
        if (!isset($session['auth']) || empty($session['auth'])) {
            $this->redirect($url);
        }
        $admin = Admin::model()->find('username=:username', array(':username'=>$session['auth']['username']));
        if (is_null($admin)) {
            $this->redirect($url);
        }
        $ret = $admin->logout();
        if ($ret === true) {
            $this->redirect($url);
        }
        $error_msg = $admin->getError('logout');
        $this->error($error_msg);
    }
}